# -*- encoding: utf-8 -*-

"""
@File:      tc_popt_fun_003.py
@Time:      2024-02-26 15:09:00
@Author:    qintingting
@Version:   1.0
@Contact:   wb-qtt862918@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    qintingting
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_popt_fun_003.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "popt popt-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline='''cat > popt_fun_003.c <<EOF
#include <stdio.h>
#include <stdlib.h>
#include <popt.h>

// 枚举定义
typedef enum { RED, GREEN, BLUE } Color;

// 全局变量，用来存储解析后的颜色值
Color color;

// 枚举映射表
struct poptOption colorOptions[] = {
    { "red", 'r', POPT_ARG_VAL, &color, RED, "Color red.", "Red color" },
    { "green", 'g', POPT_ARG_VAL, &color, GREEN, "Color green.", "Green color" },
    { "blue", 'b', POPT_ARG_VAL, &color, BLUE, "Color blue.", "Blue color" },
    POPT_TABLEEND
};

int main(int argc, char *argv[]) {
    struct poptOption optionsTable[] = {
        { "set-color", 0, POPT_ARG_INCLUDE_TABLE, colorOptions, 0, "Set the color.", "COLOR" },
        POPT_AUTOHELP
        POPT_TABLEEND
    };

    poptContext optCon = poptGetContext(NULL, argc, (const char **)argv, optionsTable, 0);
    int rc = poptGetNextOpt(optCon);

    if (rc < -1) {
        fprintf(stderr, "poptGetNextOpt failed: %s\\n", poptStrerror(rc));
        poptFreeContext(optCon);
        return 1;
    }

    switch (color) {
        case RED:
            printf("Red color selected.\\n");
            break;
        case GREEN:
            printf("Green color selected.\\n");
            break;
        case BLUE:
            printf("Blue color selected.\\n");
            break;
        default:
            printf("Unknown color selected.\\n");
            break;
    }

    poptFreeContext(optCon);
    return 0;
}
EOF
'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o popt_fun_003 popt_fun_003.c -lpopt")
        code, result = self.cmd("file popt_fun_003")
        self.assertIn("executable", result)
        code, result = self.cmd("./popt_fun_003 --red")      
        self.assertIn("Red color selected.", result)
        code, result = self.cmd("./popt_fun_003 --green")  
        self.assertIn("Green color selected.", result)
        code, result = self.cmd("./popt_fun_003 --blue")  
        self.assertIn("Blue color selected.", result)
        code, result = self.cmd("./popt_fun_003 --purple", ignore_status=True)  
        self.assertIn("unknown option", result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf popt_fun_003 popt_fun_003.c")
